package com.bieber.dubbo;

import com.bieber.dubbo.model.User;
import com.bieber.dubbo.service.MyFirstDubboService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by bieber on 2015/4/30.
 */
public class DemoConsumer {

    public static void main(String[] args) throws IOException, InterruptedException {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring/*.xml");
        BeanFactory factory = context.getAutowireCapableBeanFactory();
        final MyFirstDubboService myFirstDubboService = (MyFirstDubboService) factory.getBean("myFirstDubboService");
        int threadSize = 1000;
        final int invokeCount=1000;
        int messageSize=1024;
        final byte[] message = new byte[messageSize];
        final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        final Long[] elapsedReporter = new Long[threadSize];
        long start = System.currentTimeMillis();
        for(int i=0;i<threadSize;i++){
            Thread thread = new Thread(i+""){
                @Override
                public void run() {
                    long start = System.currentTimeMillis();
                    for(int j=0;j<invokeCount;j++){
                        myFirstDubboService.sayHello(message);
                    }
                    long elapsed = System.currentTimeMillis()-start;
                    countDownLatch.countDown();
                    elapsedReporter[Integer.parseInt(Thread.currentThread().getName())]=elapsed/invokeCount;
                }
            };
            thread.start();
        }
        countDownLatch.await();
        double elapsed = (System.currentTimeMillis()-start)/invokeCount;
        double tps = (threadSize/elapsed)*1000;
        Arrays.sort(elapsedReporter);
        System.out.println("thread size "+threadSize+" message size "+messageSize);
        System.out.println("Min elapsed:" + elapsedReporter[0]+"ms");
        System.out.println("Max elapsed:"+elapsedReporter[threadSize-1]+"ms");
        System.out.println("Tps:"+tps);
        System.out.println();
    }
}
